<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" :inline="true" width="160px" v-show="showSearch" label-width="78px">
			<el-form-item label="培训主题" prop="trainTitle">
				<el-input style="width:160px" v-model="queryParams.trainTitle" placeholder="请输入培训主题" clearable size="small" @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="主讲人" prop="master">
				<el-input style="width:160px" v-model="queryParams.master" placeholder="请输入主讲人" clearable size="small" @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="开始时间" prop="trainStartDate">
				<el-date-picker clearable size="small" style="width: 160px" v-model="queryParams.trainStartDate" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择培训开始时间">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="结束时间" prop="trainEndDate">
				<el-date-picker clearable size="small" style="width: 160px" v-model="queryParams.trainEndDate" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择培训结束时间">
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['business:personTrain:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['business:personTrain:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['business:personTrain:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['business:personTrain:export']">导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="personTrainList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="培训主题" align="center" prop="trainTitle" />
			<el-table-column label="主讲人" align="center" prop="master" />
			<el-table-column label="培训开始时间" align="center" prop="trainStartDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.trainStartDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="培训结束时间" align="center" prop="trainEndDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.trainEndDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="getTrainingRecordList(scope.row)" v-hasPermi="['business:personTrain:edit']">签到人员</el-button>
					<div v-if="scope.row.createBy == userName">
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:personTrain:edit']">修改</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['business:personTrain:remove']">删除</el-button>
					</div>
					<div v-else>
						<el-button v-if="scope.row.isSignin == '0'" size="mini" type="text" icon="el-icon-edit" @click="signin(scope.row)">签到</el-button>
						<el-button v-if="scope.row.isSignin == '1'" size="mini" type="text" icon="el-icon-delete" @click="signout(scope.row)">签出</el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改人员培训对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="120px">
				<el-form-item label="培训主题" prop="trainTitle">
					<el-input style="width:300px;" v-model="form.trainTitle" placeholder="请输入培训主题" />
				</el-form-item>
				<el-form-item label="主讲人" prop="master">
					<el-input style="width:300px;" v-model="form.master" placeholder="请输入主讲人" />
				</el-form-item>
				<el-form-item label="培训开始时间" prop="trainStartDate">
					<el-date-picker style="width:300px;" clearable size="small" v-model="form.trainStartDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择培训开始时间">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="培训结束时间" prop="trainEndDate">
					<el-date-picker style="width:300px;" clearable size="small" v-model="form.trainEndDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择培训结束时间">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="部门" prop="deptIds">
					<treeselect style="width:300px;" v-model="deptIdList" multiple value-consists-of="BRANCH_PRIORITY" :options="deptOptions" :disable-branch-nodes="true" :show-count="true" placeholder="请选择归属部门" @select="getUserList" />
				</el-form-item>
				<el-form-item label="培训人员" prop="userIdList">
					<el-checkbox v-model="allCheck" @change="allCheckChange">全选</el-checkbox>
					<el-checkbox-group v-model="userIdList">
						<el-checkbox v-for="user in userList" :label="user.userId">{{user.userName}}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="培训附件" prop="trainUrl">
					<el-upload class="upload-demo" ref="uploadRef" :action="upload" highlight-row :headers="headers" :before-upload="beforeUpload" :file-list="trainUrlList" :on-change="trainUrlChange" multiple :on-exceed="onExceed" :on-preview="onPreview" :on-remove="trainUrlChange">
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="签到附件" prop="signinUrl">
					<el-upload class="upload-demo" ref="uploadRef" :action="upload" highlight-row :headers="headers" :before-upload="beforeUpload" :file-list="signinUrlList" :on-change="signinUrlChange" multiple :on-exceed="onExceed" :on-preview="onPreview" :on-remove="signinUrlChange">
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<el-dialog title="签到记录" :visible.sync="trainingRecordVisible" width="600px" append-to-body>
			<el-table v-loading="trainingRecordLoading" :data="trainingRecordList" @selection-change="trainingRecordSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="人员名称" align="center" prop="userName" />
				<el-table-column label="签到时间" align="center" prop="startDate" width="180">
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="签出时间" align="center" prop="endDate" width="180">
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
					</template>
				</el-table-column>
			</el-table>
			<div slot="footer" class="dialog-footer">
				<el-button v-if="personTrain.createBy == userName" type="primary" @click="openSigninoutTime('in')">签 到</el-button>
				<el-button v-if="personTrain.createBy == userName" type="warning" @click="openSigninoutTime('out')">签 出</el-button>
				<el-button @click="trainingRecordVisible = false">取 消</el-button>
			</div>
		</el-dialog>
		<el-dialog :title="'签'+(signinoutTime == 'in' ? '到':'出')+'时间'" :visible.sync="signinoutTimeVisible" width="250px" append-to-body>
			<el-date-picker style="width:200px;" clearable size="small" v-model="signinoutTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" :placeholder="'选择签'+(signinoutTime == 'in' ? '到':'出')+'时间'">
			</el-date-picker>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="batchSigninout">确 定</el-button>
				<el-button @click="signinoutTimeVisible = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { listPersonTrain, trainAndTrainRecordList, getPersonTrain, delPersonTrain, addPersonTrain, updatePersonTrain } from "@/api/business/personTrain";
	import { listProject } from "@/api/business/project";
	import { addUserTrainingRecord, updateUserTrainingRecord, getTrainingRecordList } from "@/api/system/userTrainingRecord";
	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";
	import { treeselect } from "@/api/system/dept";
	import { listUser, listUserByDeptIds } from "@/api/system/user";
	import { upload } from "@/api/system/file";
	import { openMsgs, getHeaders, getFiles, downloadFile } from '@/utils/util';
	import { validatenull, uploadValidate } from '@/utils/validate'
	let _this = {}
	export default {
		name: "PersonTrain",
		components: {
			Treeselect
		},
		data() {
			_this = this
			return {
				loading: true, // 遮罩层
				ids: [], // 选中数组
				single: true, // 非单个禁用
				multiple: true, // 非多个禁用
				showSearch: true, // 显示搜索条件
				total: 0, // 总条数
				personTrainList: [], // 人员培训表格数据
				title: "", // 弹出层标题
				open: false, // 是否显示弹出层
				projectIdOptions: [], // 项目名称下拉框
				queryParams: { // 查询参数
					pageNum: 1,
					pageSize: 10,
					trainTitle: null,
					projectId: null,
					master: null,
					trainStartDate: null,
					trainEndDate: null
				},
				form: {}, // 表单参数
				rules: {}, // 表单校验
				userName: this.$store.state.user.name,
				deptOptions: [],
				userList: [],
				deptIdList: [],
				userIdList: [],
				trainingRecordVisible: false,
				trainingRecordList: [],
				trainingRecordLoading: false,
				userIdOptions: [],
				personTrain: {},
				trainingRecordSelection: [],
				upload: upload(),
				headers: getHeaders(this), //上传文件头部
				trainUrlList: [], //上传文件
				signinUrlList: [], //上传文件
				signinout: '',
				signinoutTimeVisible: false,
				signinoutTime: '',
				userIds: [],
				allCheck: false,
			};
		},
		created() {
			this.getList();
			listProject({
				pageNum: 1,
				pageSize: 1000
			}).then(response => {
				this.projectIdOptions = response.rows;
			});
			/** 查询部门下拉树结构 */
			treeselect().then(response => {
				this.deptOptions = response.data;
			});
			listUser({
				pageNum: 1,
				pageSize: 1000
			}).then(response => {
				this.userIdOptions = response.rows;
			});
		},
		methods: {
			getList() { /** 查询人员培训列表 */
				this.loading = true;
				trainAndTrainRecordList(this.queryParams).then(response => {
					this.personTrainList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			projectIdFormat(row, column) {
				return this.getOptionsLabel(this.projectIdOptions, row.projectId, 'id', 'name');
			}, // 项目名称下拉框翻译
			cancel() { // 取消按钮
				this.open = false;
				this.reset();
			},
			reset() { // 表单重置
				this.form = {
					id: null,
					delFlag: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					trainTitle: null,
					projectId: null,
					master: null,
					trainStartDate: null,
					trainEndDate: null,
					deptIds: [],
					deptIdList: [],
				};
				this.trainUrlList = []
				this.signinUrlList = []
				this.userList = []
				this.deptIdList = []
				this.allCheck = false
				this.resetForm("form");
			},
			handleQuery() { /** 搜索按钮操作 */
				this.queryParams.pageNum = 1;
				this.getList();
			},
			resetQuery() { /** 重置按钮操作 */
				this.resetForm("queryForm");
				this.handleQuery();
			},
			handleSelectionChange(selection) { // 多选框选中数据
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			trainingRecordSelectionChange(selection) { // 多选框选中数据
				this.trainingRecordSelection = selection
			},
			handleAdd() { /** 新增按钮操作 */
				this.reset();
				this.open = true;
				this.title = "添加人员培训";
			},
			handleUpdate(row) { /** 修改按钮操作 */
				this.reset();
				const id = row.id || this.ids
				getPersonTrain(id).then(response => {
					this.form = response.data;
					this.userIdList = validatenull(this.form.userIds) ? [] : this.form.userIds.split(",")
					this.deptIdList = validatenull(this.form.deptIds) ? [] : this.form.deptIds.split(",")
					this.trainUrlList = getFiles(this.form.trainUrl)
					this.signinUrlList = getFiles(this.form.signinUrl)
					if(!validatenull(this.deptIdList)) {
						this.getUserList()
					}
					this.open = true;
					this.title = "修改人员培训";
				});
			},
			submitForm() { /** 提交按钮 */
				this.$refs["form"].validate(valid => {
					if(valid) {
						let userNames = []
						for(let userId of this.userIdList) {
							userNames.push(this.getOptionsLabel(this.userList, userId, 'userId', 'userName'))
						}
						this.form.userIds = this.userIdList.join(",")
						this.form.deptIds = this.deptIdList.join(",")
						let trainUrl = []
						for(let file of this.trainUrlList) {
							trainUrl.push(file.url)
						}
						let signinUrl = []
						for(let file of this.signinUrlList) {
							signinUrl.push(file.url)
						}
						this.form.trainUrl = trainUrl.join(",")
						this.form.signinUrl = signinUrl.join(",")
						if(this.form.id != null) {
							updatePersonTrain(this.form).then(response => {
								if(response.code === 200) {
									this.msgSuccess("修改成功");
									this.open = false;
									this.getList();
								}
							});
						} else {
							addPersonTrain(this.form).then(response => {
								if(response.code === 200) {
									this.msgSuccess("新增成功");
									this.open = false;
									this.getList();
								}
							});
						}
					}
				});
			},
			handleDelete(row) { /** 删除按钮操作 */
				const ids = row.id || this.ids;
				this.$confirm('是否确认删除人员培训编号为"' + ids + '"的数据项?', "警告", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(function() {
					return delPersonTrain(ids);
				}).then(() => {
					this.getList();
					this.msgSuccess("删除成功");
				}).catch(function() {});
			},
			handleExport() { /** 导出按钮操作 */
				this.download('business/personTrain/export', {
					...this.queryParams
				}, `人员培训.xlsx`)
			},
			signin(data) {
				let form = {
					'userId': this.$store.state.user.userId,
					'trainId': data.id,
					startDate: new Date()
				}
				addUserTrainingRecord(form).then(response => {
					if(response.code === 200) {
						this.msgSuccess("签到成功");
						this.open = false;
						this.getList();
					}
				});
			},
			openSigninoutTime(signinout) {
				if(this.trainingRecordSelection.length == 0) {
					this.msgError("请选择签到人员");
					return false
				}
				if(signinout == 'in') {
					this.userIds = []
					for(let d of this.trainingRecordSelection) {
						if(validatenull(d.startDate)) {
							this.userIds.push(d.userId)
						} else {
							this.msgError("签到人员中包含已签到");
							return false
						}
					}
				} else {
					this.userIds = []
					for(let d of this.trainingRecordSelection) {
						if(validatenull(d.startDate)) {
							this.msgError("签到人员中包含未签到");
							return false
						} else if(!validatenull(d.endDate)) {
							this.msgError("签到人员中包含已签出");
							return false
						} else {
							this.userIds.push(d.userId)

						}
					}
				}
				this.signinout = signinout
				this.signinoutTimeVisible = true
				this.signinoutTime = ''
			},
			batchSigninout() {
				if(this.signinout == 'in') {
					let form = {
						'userIds': this.userIds.join(","),
						'trainId': this.personTrain.id,
						startDate: this.signinoutTime
					}
					addUserTrainingRecord(form).then(response => {
						if(response.code === 200) {
							this.msgSuccess("签到成功");
							this.signinoutTimeVisible = false
							this.trainingRecordVisible = false;
							this.getList();
						}
					});
				} else {
					let form = {
						'userIds': this.userIds.join(","),
						'trainId': this.personTrain.id,
						endDate: this.signinoutTime
					}
					updateUserTrainingRecord(form).then(response => {
						if(response.code === 200) {
							this.msgSuccess("签到成功");
							this.signinoutTimeVisible = false
							this.trainingRecordVisible = false;
							this.getList();
						}
					});
				}
			},
			signout(data) {
				let form = {
					'userId': this.$store.state.user.userId,
					'trainId': data.id
				}
				updateUserTrainingRecord(form).then(response => {
					if(response.code === 200) {
						this.msgSuccess("签到成功");
						this.getList();
					}
				});
			},
			getTrainingRecordList(data) {
				this.trainingRecordVisible = true
				this.trainingRecordLoading = true
				this.personTrain = data
				getTrainingRecordList({
					'trainId': data.id,
					'userIds': data.userIds
				}).then(response => {
					if(response.code === 200) {
						let data = response.data
						for(let d of data) {
							d.userName = this.getOptionsLabel(this.userIdOptions, d.userId, 'userId', 'userName')
						}
						this.trainingRecordList = data
					}
					this.trainingRecordLoading = false
				});
			},
			getUserList() {
				setTimeout(() => {
					listUserByDeptIds(_this.deptIdList).then(response => {
						let data = response.data
						let userList = []
						for(let d of data) {
							userList.push({
								'userName': d.userName,
								'userId': d.userId + ""
							})
						}
						_this.userList = userList;
					});
				}, 100)
			},
			beforeUpload(file) { //上传格式
				return uploadValidate(this, file, 'import', '', -1);
			},
			onExceed(files, fileList) {
				openMsgs(this, '', `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`, true, 'warning', 0);
			},
			trainUrlChange(file, fileList) {
				let files = []
				if(file.status == "success") {
					for(let f of fileList) {
						files.push({
							"name": f.name,
							"url": validatenull(f.response) ? f.url : f.response.msg
						})
					}
					this.trainUrlList = files
				}
			},
			signinUrlChange(file, fileList) {
				let files = []
				if(file.status == "success") {
					for(let f of fileList) {
						files.push({
							"name": f.name,
							"url": validatenull(f.response) ? f.url : f.response.msg
						})
					}
					this.signinUrlList = files
				}
			},
			onPreview(file) {
				downloadFile(file)
			},
			allCheckChange() {
				if(this.allCheck) {
					this.userIdList = this.userList.map(item => item.userId)
				} else {
					this.userIdList = []
				}
			}
		}
	};
</script>
<style rel="stylesheet/scss" lang="scss">
	.el-form-item__content {
		line-height: 15px!important;
	}
</style>